﻿/*
 * 由SharpDevelop创建。
 * 用户： Administrator
 * 日期: 2022/4/3
 * 时间: 下午 19:54
 * 
 * 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
 */
using System;
using System.Windows.Forms;
using System.Data;
using System.Net.NetworkInformation;

namespace NetcardStatusDisplay
{
    /// <summary>
    /// Description of MainForm.
    /// </summary>
    public partial class MainForm : Form
    {
        BindingSource gBs = new BindingSource();
        DataTable gDt = new DataTable();
        Timer tick = new Timer();
        
        public MainForm()
        {
            InitializeComponent();

            Text += "_" + System.IO.File.GetLastWriteTime(this.GetType().Assembly.Location).ToString("d");	//窗口标题显示编译日期
            InitDatable();
            
            tick.Tick += TimerForm_Tick;
            tick.Interval = 1000;
            tick.Start();                   //开启定时状态更新
        }
        
        private void TimerForm_Tick(object sender, EventArgs e)
        {
            ThreadUpdateInfo();
        }

        private void InitDatable()
        {
            //新建列并添加
            gDt.Columns.Add(new DataColumn("名称", typeof(string)));
            gDt.Columns.Add(new DataColumn("状态", typeof(string)));
            gDt.Columns.Add(new DataColumn("连接速率", typeof(string)));
            gDt.Columns.Add(new DataColumn("MAC", typeof(string)));
            gDt.Columns.Add(new DataColumn("描述", typeof(string)));
            DataColumn colID = new DataColumn("ID", typeof(string));
            gDt.Columns.Add(colID);
            gDt.PrimaryKey = new DataColumn[] { colID };    //ID列设置为主键
            gBs.DataSource = gDt;                           //DataTable绑定到BindingSource
            dataGridView1.DataSource = gBs;                 //再把BindingSource绑定到dataGridView
            //设置列宽
            dataGridView1.Columns[0].Width = 120;
            dataGridView1.Columns[1].Width = 90;
            dataGridView1.Columns[2].Width = 80;
            dataGridView1.Columns[3].Width = 120;
            dataGridView1.Columns[4].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;    //描述列填充剩余宽度
            dataGridView1.Columns[5].Visible = false;       //ID列不可见
        }

        /// <summary>
        ///开始查询网卡信息
        /// </summary>
        private void ThreadUpdateInfo()
        {
            try
            {
                using (DataTable _dt = gDt.Clone()) {
                    NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
                    foreach (NetworkInterface adapter in adapters)
                    {
                        if (adapter.NetworkInterfaceType == NetworkInterfaceType.Loopback)
                            continue;

                        DataRow dr = _dt.NewRow();
                        //网卡名称
                        dr[0] = adapter.Name;
                        //连接状态
                        dr[1] = adapter.OperationalStatus.ToString();
                        //连接速率
                        if (adapter.OperationalStatus == OperationalStatus.Up)
                        {
                            if (adapter.Speed >= 1000000000)
                                dr[2] = string.Format("{0:0.##} Gbps", adapter.Speed / 1000000000.0);   //有小数时显示小数 无小数显示整数
                            else if (adapter.Speed >= 1000000)
                                dr[2] = string.Format("{0:0.##} Mbps", adapter.Speed / 1000000.0);
                            else if (adapter.Speed >= 1000)
                                dr[2] = string.Format("{0:0.##} Kbps", adapter.Speed / 1000.0);
                            else
                                dr[2] = string.Format("{0} bps", adapter.Speed);
                        }
                        else
                            dr[2] = "";
                        //MAC
                        dr[3] = adapter.GetPhysicalAddress().ToString();
                        //描述
                        dr[4] = adapter.Description;
                        //GUID
                        dr[5] = adapter.Id;
                        _dt.Rows.Add(dr);
                    }
                    while (_dt.Rows.Count < gDt.Rows.Count)     //实际网卡数量比已经显示的少，需要删除
                    {
                        //遍历界面显示的项，检查ID，不在前面新获取到的表中说明网卡已经不存在，需要从界面绑定的表中删除
                        foreach (DataRow item in gDt.Rows)
                        {
                            bool isHave = false;                //是否已存在
                            for (int m = 0; m < _dt.Rows.Count; m++)
                            {
                                if (_dt.Rows[m][5].ToString() == item[5].ToString())    //主键相等说明该项仍然存在
                                {
                                    isHave = true;
                                    break;
                                }
                            }
                            if (!isHave)                        //不存在的项需要删除
                            {
                                gDt.Rows.Remove(item);
                                break;
                            }
                        }
                    }
                    //遍历新获取的表，界面绑定的表中已存在则更新，不存在则说明有新增项，需要添加
                    foreach (DataRow item in _dt.Rows)
                    {
                        bool isHave = false;                    //是否已存在
                        for (int m = 0; m < gDt.Rows.Count; m++)
                        {
                            if (gDt.Rows[m][5].ToString() == item[5].ToString())  //主键相等
                            {
                                gDt.Rows[m][1] = item[1];       //更新连接状态
                                gDt.Rows[m][2] = item[2];       //更新速率
                                gDt.Rows[m][3] = item[3];       //更新MAC
                                isHave = true;
                                break;
                            }
                        }
                        if (!isHave)                            //不存在则需要添加进去
                        {
                            DataRow newRow = gDt.NewRow();
                            newRow.ItemArray = item.ItemArray;
                            gDt.Rows.Add(newRow);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 获取ConnectionStatus数字对应的中文描述
        /// </summary>
        /// <param name="str">字符串格式的ConnectionStatus数字</param>
        /// <returns></returns>
        string GetNetConnectionStatusString(string str)
        {
            try {
                uint status = Convert.ToUInt16(str);
                switch (status) {
                    case 0: return "已禁用";
                    case 1: return "正在连接";
                    case 2: return "已连接";
                    case 3: return "正在断开";
                    case 4: return "硬件不存在";
                    case 5: return "硬件已禁用";
                    case 6: return "硬件故障";
                    case 7: return "未连接";
                    case 8: return "正在认证";
                    case 9: return "认证成功";
                    case 10: return "认证失败";
                    case 11: return "地址无效";
                    case 12: return "要求认证";
                    default: return "未知状态" + status;
                }
            } catch (Exception) {
                return "错误状态";
            }
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            gBs.Dispose();
            gBs = null;
            gDt.Dispose();
            gDt = null;
        }
    }
}
